package com.luxuewen.sxa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luxuewen.sxa.entity.SxaDepartments;
import com.luxuewen.sxa.service.SxaDepartmentsService;
import com.luxuewen.sxa.mapper.SxaDepartmentsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
* @author wen
* @description 针对表【sxa_departments】的数据库操作Service实现
* @createDate 2023-11-01 16:28:52
*/
@Service
public class SxaDepartmentsServiceImpl extends ServiceImpl<SxaDepartmentsMapper, SxaDepartments>
    implements SxaDepartmentsService{
    @Autowired
    private CommonServiceImpl commonService;

    /**
     * 获取部门选项
     */
    public List<Map<String, Object>> options () {
        QueryWrapper<SxaDepartments> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
                .select("id", "sort", "name as label", "parent_id", "remark", "status", "created_at")
                .orderByAsc("sort");

        return queryList(wrapper);
    }

    public List<Map<String, Object>> getList (String search) {
        QueryWrapper<SxaDepartments> wrapper = new QueryWrapper<>();
        wrapper.like("name", search)
                .select("id", "sort", "name as label", "parent_id", "remark", "status", "created_at")
                .orderByAsc("sort");

        return queryList(wrapper);
    }

    public List<Map<String, Object>> queryList (QueryWrapper<SxaDepartments> wrapper) {
        List<Map<String, Object>> depts = this.listMaps(wrapper);
        List<Map<String, Object>> data = new ArrayList<>();
        if (!depts.isEmpty()) {
            // 首先获取根节点
            for (Map<String, Object> parent : depts) {
                if (parent.get("parent_id").equals(0)) {
                    data.add(parent);
                }
            }

            // 存在根节点
            if (!data.isEmpty()) {
                // 获取子节点
                depts = commonService.tree(depts, data);
            }
        }

        return depts;
    }
}




